/*  Copyright (c) 2012 William Rogers and James Boud

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using System.Windows.Forms;
using System.Drawing;

using TInput = Microsoft.Xna.Framework.Content.Pipeline.Graphics.FontDescription;
using TOutput = JBBRXG11ContentSpriteFont.FontInfoStuff;

namespace JBBRXG11ContentSpriteFont
{
    [ContentProcessor(DisplayName = "JBBRXG11 Sprite Font Processor")]
    public class JBBRXG11SpriteFontContentProcessor : ContentProcessor<TInput, TOutput>
    {
        public override TOutput Process(TInput input, ContentProcessorContext context)
        {
            FontInfoStuff fis = new FontInfoStuff();
            fis.FontName = input.FontName;
            fis.spacing = input.Spacing;

            fis.chardata = new charinfo[input.Characters.Count + 1];  // Add 1 for default character
            fis.havedefaultchar = false;
            fis.chardata[0].ch = '@';
            if (input.DefaultCharacter != null)
            {
                bool ok = false;
                foreach (char ch in input.Characters)
                {
                    if (ch == (char)input.DefaultCharacter)
                    {
                        ok = true;
                        break;
                    }
                }
                if (!ok)
                    throw new Exception("Cannot use " + ((char)input.DefaultCharacter).ToString()
                                      + " as default character as it isn't in the font");
                fis.havedefaultchar = true;
                fis.chardata[0].ch = (char)input.DefaultCharacter;
            }
            fis.defaultcharindex = 0;
            int c = 1;
            foreach (char ch in input.Characters)
            {
                fis.chardata[c++].ch = ch;
            }

            Bitmap texture;
            texture = makefonttexture(fis, input.Size, input.Style, input.UseKerning);
            makeAlpha8texture(fis, texture);

            return fis;
        }

        Bitmap makefonttexture(FontInfoStuff fis,
                               float fsize,
                               FontDescriptionStyle fstyle,
                               bool fkerning)
        {
            // The use kerning instruction is ignored - don't know how to get kerning pairs
            Form dummywindow = new Form();
            Graphics g = dummywindow.CreateGraphics();
            FontStyle style = FontStyle.Regular;
            if (fstyle == FontDescriptionStyle.Bold) style = FontStyle.Bold;
            if (fstyle == FontDescriptionStyle.Italic) style = FontStyle.Italic;
            Font GDIfont = new Font(fis.FontName, fsize, style);

            SizeF sizeone, sizetwo;
            sizeone = g.MeasureString("A", GDIfont);
            sizetwo = g.MeasureString("A\r\nA", GDIfont);
            fis.linespacing = (int)(sizetwo.Height - sizeone.Height + 0.999f);

            for (int c = 0; c < fis.chardata.Length; c++)
            {
                char ch = fis.chardata[c].ch;
                fis.chardata[c].ch = ch;
                sizeone = g.MeasureString(ch.ToString(), GDIfont);
                fis.chardata[c].width = (int)(sizeone.Width);
                fis.chardata[c].height = (int)(sizeone.Height);
                sizetwo = g.MeasureString(ch.ToString() + ch.ToString(), GDIfont);
                fis.chardata[c].stride = sizetwo.Width - sizeone.Width;
                // Stride doesn't work for the space char
                // Using width as stride if value very small fixes that
                // Have no idea what other trouble it might cause
                if (fis.chardata[c].stride < 0.01f) fis.chardata[c].stride = fis.chardata[c].width;
            }

            fis.texturewidth = 8;
            for (; ; )
            {
                if (tryfit(fis.chardata, fis.texturewidth, out fis.textureheight)) break;
                fis.texturewidth *= 2;
                if (fis.texturewidth > 2048)
                    throw new Exception("Font is too large to be placed on one texture (2048*2048)");
            }

            Bitmap texture = new Bitmap(fis.texturewidth, fis.textureheight);
            Graphics gbm = Graphics.FromImage(texture);
            gbm.FillRectangle(Brushes.Black, new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height));
            for (int c = 0; c < fis.chardata.Length; c++)
            {
                gbm.DrawString(fis.chardata[c].ch.ToString(), GDIfont, Brushes.White, fis.chardata[c].x, fis.chardata[c].y);
            }

            return texture;
        }

        bool tryfit(charinfo[] data, int width, out int height)
        {
            // See if the font data can fit onto a bitmap
            // of the given width (squared)
            int x, y, ht;
            height = 0;
            x = 0; y = 0; ht = 0;
            for (int c = 0; c < data.Length; c++)
            {
                if (x + data[c].width > width)
                {
                    x = 0;
                    y += ht;
                    ht = 0;
                    if (data[c].width > width) return false;
                }
                if (data[c].height > ht) ht = data[c].height;
                data[c].x = x;
                data[c].y = y;
                x += data[c].width;
            }
            height = y + ht;
            if (height > width) return false;
            return true;
        }

        void makeAlpha8texture(FontInfoStuff fis, Bitmap texture)
        {
            byte[] texdata;
            int x, y, index;

            texdata = new byte[fis.texturewidth * fis.textureheight];
            index = 0;
            for (y = 0; y < fis.textureheight; y++)
            {
                for (x = 0; x < fis.texturewidth; x++)
                {
                    texdata[index++] = texture.GetPixel(x, y).G;
                }
            }

            fis.texturedata = texdata;
        }
    }
}
